import { parseToken, getRefreshToken } from "@/utils/token";
import store from "../store";
// 判断用户是否已登录
export async function testTokenState() {
  let bearerToken = localStorage.getItem("bearerToken") || "";
  let refreshToken = localStorage.getItem("refreshToken") || "";
  let token;
  if (bearerToken) {
    token = bearerToken.replace(/Bearer\s*/i, "");
    let exp = parseToken(token).payload.exp;
    if (new Date().getTime() - exp * 1000 > 0) {
      //token 过期 尝试刷新token
      if (refreshToken) {
        // 虽然refreshToken一定存在，还是判断下防止特殊情况报错 hhh
        refreshToken = await getRefreshToken();
        localStorage.setItem("refreshToken", refreshToken);
        if (refreshToken.length !== 0) {
          //刷新成功
          store.commit("user/tokenState", "notExpired");
        } else {
          //刷新失败
          store.commit("user/tokenState", "Expired");
        }
      }
    } else {
      //token未过期
      store.commit("user/tokenState", "notExpired");
    }
  } else {
    //未登录
    store.commit("user/tokenState", "Expired");
  }
}
